# utils/settings_manager.py
import os
import json
import logging
from PySide6.QtCore import QSettings, QStandardPaths

# 配置日志记录
logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')

class SettingsManager:
    """应用设置管理器"""

    def __init__(self):
        # 设置文件路径
        self._settings_file = self._get_settings_file_path()

        # 应用默认设置
        self._default_settings = {
            "window": {
                "geometry": None,
                "state": None
            },
            "data": {
                "last_project_path": "",
                "import_directory": "",
                "export_directory": ""
            },
            "visualization": {
                "default_view": "vertical",
                "curve_colors": {}
            },
            "language": "zh_CN"
        }

        # 当前设置
        self._settings = self._load_settings()

    def _get_settings_file_path(self) -> str:
        """获取设置文件路径"""
        # 获取应用配置目录
        config_dir = QStandardPaths.writableLocation(QStandardPaths.AppConfigLocation)

        # 确保目录存在
        if not os.path.exists(config_dir):
            os.makedirs(config_dir)

        # 返回设置文件路径
        return os.path.join(config_dir, "settings.json")

    def _load_settings(self) -> dict:
        """加载设置"""
        try:
            if os.path.exists(self._settings_file):
                with open(self._settings_file, 'r', encoding='utf-8') as f:
                    settings = json.load(f)

                    # 合并默认设置，确保所有必需的键都存在
                    return {**self._default_settings, **settings}
            else:
                # 使用默认设置
                return self._default_settings
        except Exception as e:
            logging.error(f"加载设置失败: {str(e)}")
            return self._default_settings

    def save_settings(self) -> None:
        """保存设置"""
        try:
            with open(self._settings_file, 'w', encoding='utf-8') as f:
                json.dump(self._settings, f, ensure_ascii=False, indent=2)
        except Exception as e:
            logging.error(f"保存设置失败: {str(e)}")

    def _get_nested_value(self, keys):
        current = self._settings
        for k in keys:
            if k in current:
                current = current[k]
            else:
                return None
        return current

    def _set_nested_value(self, keys, value):
        current = self._settings
        for k in keys[:-1]:
            if k not in current:
                current[k] = {}
            current = current[k]
        current[keys[-1]] = value

    def get_setting(self, key: str, default=None):
        """获取设置值"""
        keys = key.split('.')
        result = self._get_nested_value(keys)
        return result if result is not None else default

    def set_setting(self, key: str, value) -> None:
        """设置设置值"""
        keys = key.split('.')
        self._set_nested_value(keys, value)

        # 保存设置
        self.save_settings()

    def get_window_geometry(self) -> bytes:
        """获取窗口几何数据"""
        return self.get_setting("window.geometry")

    def set_window_geometry(self, geometry: bytes) -> None:
        """设置窗口几何数据"""
        if isinstance(geometry, bytes):
            self.set_setting("window.geometry", geometry)
        else:
            logging.error("窗口几何数据必须是字节类型")

    def get_window_state(self) -> bytes:
        """获取窗口状态数据"""
        return self.get_setting("window.state")

    def set_window_state(self, state: bytes) -> None:
        """设置窗口状态数据"""
        if isinstance(state, bytes):
            self.set_setting("window.state", state)
        else:
            logging.error("窗口状态数据必须是字节类型")

    def get_last_project_path(self) -> str:
        """获取上次打开的项目路径"""
        return self.get_setting("data.last_project_path", "")

    def set_last_project_path(self, path: str) -> None:
        """设置上次打开的项目路径"""
        if isinstance(path, str):
            self.set_setting("data.last_project_path", path)
        else:
            logging.error("项目路径必须是字符串类型")

    def get_import_directory(self) -> str:
        """获取导入目录"""
        return self.get_setting("data.import_directory", "")

    def set_import_directory(self, path: str) -> None:
        """设置导入目录"""
        if isinstance(path, str):
            self.set_setting("data.import_directory", path)
        else:
            logging.error("导入目录必须是字符串类型")

    def get_export_directory(self) -> str:
        """获取导出目录"""
        return self.get_setting("data.export_directory", "")

    def set_export_directory(self, path: str) -> None:
        """设置导出目录"""
        if isinstance(path, str):
            self.set_setting("data.export_directory", path)
        else:
            logging.error("导出目录必须是字符串类型")

    def get_default_view(self) -> str:
        """获取默认视图类型"""
        return self.get_setting("visualization.default_view", "vertical")

    def set_default_view(self, view_type: str) -> None:
        """设置默认视图类型"""
        if isinstance(view_type, str):
            self.set_setting("visualization.default_view", view_type)
        else:
            logging.error("默认视图类型必须是字符串类型")

    def get_curve_color(self, curve_name: str) -> str:
        """获取曲线颜色"""
        curve_colors = self.get_setting("visualization.curve_colors", {})
        return curve_colors.get(curve_name, "#FF0000")  # 默认红色

    def set_curve_color(self, curve_name: str, color: str) -> None:
        """设置曲线颜色"""
        if isinstance(curve_name, str) and isinstance(color, str):
            curve_colors = self.get_setting("visualization.curve_colors", {})
            curve_colors[curve_name] = color
            self.set_setting("visualization.curve_colors", curve_colors)
        else:
            logging.error("曲线名称和颜色必须是字符串类型")

    def get_language(self) -> str:
        """获取语言设置"""
        return self.get_setting("language", "zh_CN")

    def set_language(self, language: str) -> None:
        """设置语言"""
        if isinstance(language, str):
            self.set_setting("language", language)
        else:
            logging.error("语言设置必须是字符串类型")